<?php

namespace app\api\controller;

use app\BaseController;
use app\service\WxTplService;
use think\facade\Db;
use think\facade\Log;

class WechatMsg extends BaseController
{
    public function test(){
        $staff=Db::table("staff")->where("id",1)->find();
        $strangeApply=Db::table("stranger_apply")->where("id",224)->find();
        $res=(new WxTplService())->sendVerifyMsg($strangeApply,$staff);
        var_dump($res);
    }
    public function verify(){
        $path=dir(getcwd())->path.'/log/wechat/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        $address = $path."/".date('His').rand(100000,999999).'.txt';
        file_put_contents($address,file_get_contents("php://input"),FILE_APPEND);
        parse_str(file_get_contents($address),$result);//读取文本并变成数组
        //signature=f464b24fc39322e44b38aa78f5edd27bd1441696&echostr=4375120948345356249&timestamp=1714036504&nonce=1514711492
        $signature=request()->get("signature");
        $echostr=request()->get("echostr");
        $timestamp=request()->get("timestamp");
        $nonce=request()->get("nonce");
        $token=env("APP.WECHAT_MESSAGE_TOKEN");
        $str=$nonce.$timestamp.$token;
        $sign=sha1($str);
        //Log::error( file_get_contents("php://input"));
        Log::error('echostr'.$echostr,["yangzl"=>"yangzl"]);
        Log::error('timestamp  '.$timestamp,["yangzl"=>"yangzl"]);
        Log::error('nonce  '.$nonce,["yangzl"=>"yangzl"]);
        Log::error('sign   '.$sign,["yangzl"=>"yangzl"]);
        Log::error('signature   '.$signature,["yangzl"=>"yangzl"]);
        exit($echostr) ;
        if($sign==$signature){
            exit($echostr) ;
        }else{

        }

    }

    public function msg(){

        //获取全局token
        $token = $this->getToken();
        $template_id="6s2cLvGshWcEUmneVHT1MmEHLfoxyTBjn_q3XOk9REY";
        $url="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$token; //模板信息请求地址
        //https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN
        //发送的模板信息(微信要求json格式，这里为数组（方便添加变量）格式，然后转为json)
        $post_data = array(
            "touser"=>"ohcFN5ZmEd995RZMMG6KKYXQa5Mc", //推送给谁,openid
            "template_id"=>$template_id, //微信后台的模板信息id
            "page"=>"pages/admin/stranger/index",
            "data"=> array(
                "thing9" => array(
                    "value"=>"早早",
                    "color"=>"#173177"
                ),
                "thing5" => array(
                    "value"=>"yangzl",//钥匙名称
                    "color"=>"#173177"
                ),
                "phone_number6" => array(
                    "value"=>"18856151031",//用户名称
                    "color"=>"#173177"
                ),

                "thing1" => array(
                    "value"=>"外卖",//审核类型
                    "color"=>"#173177"
                ),
                "phrase7"=>array(
                    "value"=>"待审核",
                    "color"=>"#ff8c00"
                ),
            )
        );
        //将上面的数组数据转为json格式
        $post_data = json_encode($post_data);
        $data=$this->curl_post($url,$post_data);
        var_dump($data);exit;
        if($data["errcode"]=="0"){
//            $info["template_id"]=$template_id;
//            $info["con"]=$msg;
//            $info["msgid"]=$data["msgid"];
//            $info["openid"]=$openid;
//            Db::connect($this->config)->table("msglog")->insert($info);
        }
        return $data;
    }
    /**
     * @param $url
     * @param array $data
     * @return mixed
     * curl请求
     */
    function curl_post($url , $post_data=''){

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url); //设置发送数据的网址
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设置有返回值，0，直接显示
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0); //禁用证书验证
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);//post请求发送的数据包
        //接收执行返回的数据
        $data = curl_exec($ch);
        //关闭句柄
        curl_close($ch);
        $data = json_decode($data,true); //将json数据转成数组
        return $data;
    }
    public function getToken(){
        $redis=new \Redis;
        $redis->connect("127.0.0.1",6379);
        $redis->auth(env('APP.REDIS_PASSWORD'));
        if($redis->exists("wx_access_token")){
            return $redis->get("wx_access_token");
        }else{
            $appid=env('APP.WECHAT_MINI_APPID');
            $secret=env('APP.WECHAT_MINI_SECRET');
            $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
            $result=file_get_contents($url);

            $result=json_decode($result,true);

            $redis->set("wx_access_token", $result["access_token"], 7200);
            return $result["access_token"];
        }

    }

}